import React, { useState, useEffect, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import TopNavbar from '../../components/TopNavbar'
import ErrorBoundary from '../../components/ErrorBoundary'
import styles from './index.module.css'
import { loadBills, updateBillStatus } from '../../services/paymentService'
import { Popup, Toast } from 'antd-mobile'
import { createAlipayOrder } from '../../services/payService'

const Payment = () => {
  const navigate = useNavigate()
  const [bills, setBills] = useState([])
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState('待缴费')
  const [selected, setSelected] = useState(new Set())
  const [showSheet, setShowSheet] = useState(false)
  const [sheetBill, setSheetBill] = useState(null)

  // 从本地加载账单

  useEffect(() => {
    setLoading(true)
    const data = loadBills()
    setBills(data)
    setLoading(false)
  }, [])

  const list = useMemo(() => bills.filter(b => (activeTab === '待缴费' ? b.status === '待缴费' : b.status === '已缴费')), [bills, activeTab])

  const totalAmount = useMemo(() => {
    let sum = 0
    list.forEach(b => { if (selected.has(b.id)) sum += Number(b.amount || 0) })
    return sum.toFixed(2)
  }, [list, selected])

  const getStatusColor = (status) => {
    switch (status) {
      case '待缴费':
        return '#ff4d4f'
      case '已缴费':
        return '#52c41a'
      case '已过期':
        return '#666'
      default:
        return '#666'
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case '待缴费':
        return '⏰'
      case '已缴费':
        return '✅'
      case '已过期':
        return '❌'
      default:
        return '❓'
    }
  }

  const handlePayment = async (bill) => {
    if (bill.status !== '待缴费') return
    try {
      Toast.show({ content: '创建支付订单...', duration: 800 })
      const resp = await createAlipayOrder({
        orderNo: bill.billNo || bill.id,
        totalPrice: Number(bill.amount).toFixed(2),
        subject: bill.billType || '门诊缴费'
      })
      // 兼容后端返回结构：{ code, msg, url }
      const redirectUrl = resp?.url || resp?.data?.url
      if (resp?.code === 200 && redirectUrl) {
        window.location.href = redirectUrl
      } else if (redirectUrl) {
        window.location.href = redirectUrl
      } else {
        throw new Error(resp?.msg || '未获取到跳转地址')
      }
    } catch (e) {
      Toast.show({ content: e.message || '发起支付失败', position: 'center' })
    }
  }

  const toggleSelect = (id) => {
    setSelected(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const toggleSelectAll = () => {
    const ids = list.map(b => b.id)
    const allSelected = ids.every(id => selected.has(id))
    setSelected(allSelected ? new Set() : new Set(ids))
  }

  const paySelected = async () => {
    const selectedBills = list.filter(b => selected.has(b.id))
    if (selectedBills.length === 0) return
    if (selectedBills.length > 1) {
      Toast.show({ content: '演示环境暂不支持合并支付，请单个支付', position: 'center' })
      return
    }
    await handlePayment(selectedBills[0])
  }

  const handleBillDetail = (bill) => {
    // 已缴费进入详情页；待缴费打开明细弹层
    if (bill.status === '已缴费') {
      navigate(`/payment/${bill.id}`)
    } else {
      setSheetBill(bill)
      setShowSheet(true)
    }
  }

  if (loading) {
    return (
      <div className={styles.paymentPage}>
        <ErrorBoundary>
          <TopNavbar
            title="门诊缴费"
            showBack={true}
            onBack={() => navigate(-1)}
          />
        </ErrorBoundary>
        <div className={styles.loadingContainer}>
          <div className={styles.loadingSpinner}></div>
          <div className={styles.loadingText}>加载中...</div>
        </div>
      </div>
    )
  }

  if (bills.length === 0) {
    return (
      <div className={styles.paymentPage}>
        <ErrorBoundary>
          <TopNavbar
            title="门诊缴费"
            showBack={true}
            onBack={() => navigate(-1)}
          />
        </ErrorBoundary>
        <div className={styles.content}>
          <div className={styles.emptyState}>
            <div className={styles.emptyIcon}>💰</div>
            <div className={styles.emptyText}>暂无待缴费账单</div>
            <div className={styles.emptySubtext}>您当前没有需要缴费的账单</div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.paymentPage}>
      <ErrorBoundary>
        <TopNavbar
          title="门诊缴费"
          showBack={true}
          onBack={() => navigate(-1)}
        />
      </ErrorBoundary>
      
      <div className={styles.content}>
        <div className={styles.tabs}>
          <div className={`${styles.tab} ${activeTab === '待缴费' ? styles.tabActive : ''}`} onClick={() => setActiveTab('待缴费')}>待缴费</div>
          <div className={`${styles.tab} ${activeTab === '已缴费' ? styles.tabActive : ''}`} onClick={() => setActiveTab('已缴费')}>已缴费</div>
        </div>
        <div className={styles.billsList}>
          {list.map((bill) => (
            <div key={bill.id} className={styles.billCard}>
              <div className={styles.billHeader}>
                <div className={styles.billId}>
                  账单号: {bill.billNo}
                </div>
                <div 
                  className={styles.billStatus}
                  style={{ color: getStatusColor(bill.status) }}
                >
                  {getStatusIcon(bill.status)} {bill.status}
                </div>
              </div>
              
              <div className={styles.billInfo}>
                {bill.status === '待缴费' && (
                  <div className={styles.selectRow}>
                    <label className={styles.checkboxLabel}>
                      <input type="checkbox" checked={selected.has(bill.id)} onChange={() => toggleSelect(bill.id)} />
                      <span>选择该账单</span>
                    </label>
                  </div>
                )}
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>患者姓名:</span>
                  <span className={styles.infoValue}>{bill.patientName}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>科室:</span>
                  <span className={styles.infoValue}>{bill.department}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>医生:</span>
                  <span className={styles.infoValue}>{bill.doctorName}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>账单日期:</span>
                  <span className={styles.infoValue}>{bill.billDate}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>账单类型:</span>
                  <span className={styles.infoValue}>{bill.billType}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>金额:</span>
                  <span className={styles.infoValue}>¥{bill.amount}</span>
                </div>
              </div>
              
              <div className={styles.billActions}>
                <button 
                  className={styles.actionBtn}
                  onClick={() => handleBillDetail(bill)}
                >
                  {bill.status === '待缴费' ? '缴费明细' : '缴费详情'}
                </button>
                {bill.status === '待缴费' && (
                  <button 
                    className={`${styles.actionBtn} ${styles.payBtn}`}
                    onClick={() => handlePayment(bill)}
                  >
                    立即缴费
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
        <div className={styles.footerBar}>
          <label className={styles.checkboxLabel}>
            <input type="checkbox" onChange={toggleSelectAll} checked={list.length > 0 && list.every(b => selected.has(b.id))} />
            <span>全选（已选 {selected.size} 张）</span>
          </label>
          <div className={styles.total}>合计：<span className={styles.totalAmount}>¥ {totalAmount}</span></div>
          <button className={styles.payPrimary} onClick={paySelected} disabled={selected.size === 0}>去缴费</button>
        </div>
      </div>

      <Popup visible={showSheet} onMaskClick={() => setShowSheet(false)} onClose={() => setShowSheet(false)} bodyStyle={{ borderTopLeftRadius: 12, borderTopRightRadius: 12, padding: 16 }}>
        <div style={{ fontWeight: 700, textAlign: 'center', marginBottom: 8 }}>缴费明细</div>
        {sheetBill && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <div><span style={{ background: '#e6f4ff', color: '#1677ff', padding: '2px 6px', borderRadius: 6, marginRight: 6 }}>药</span>药品</div>
              <div>小计：¥ 100.13</div>
            </div>
            <ol style={{ paddingLeft: 20, color: '#333' }}>
              <li>寇宫止血颗粒*3盒 <span style={{ float: 'right' }}>¥ 50.13</span></li>
              <li>维生素B1*2瓶 <span style={{ float: 'right' }}>¥ 20.00</span></li>
              <li>维生素B2*2瓶 <span style={{ float: 'right' }}>¥ 10.00</span></li>
              <li>维生素E*2瓶 <span style={{ float: 'right' }}>¥ 10.00</span></li>
              <li>维生素C*2瓶 <span style={{ float: 'right' }}>¥ 10.00</span></li>
            </ol>
            <div style={{ display: 'flex', justifyContent: 'space-between', margin: '12px 0 8px' }}>
              <div><span style={{ background: '#fff7e6', color: '#faad14', padding: '2px 6px', borderRadius: 6, marginRight: 6 }}>查</span>检查</div>
              <div>小计：¥ 420.00</div>
            </div>
            <ol style={{ paddingLeft: 20, color: '#333' }}>
              <li>CT <span style={{ float: 'right' }}>¥ 200.00</span></li>
              <li>上腹部CT平扫 <span style={{ float: 'right' }}>¥ 220.00</span></li>
            </ol>
            <div style={{ textAlign: 'right', fontWeight: 700, paddingTop: 8 }}>合计：<span>¥ {Number(sheetBill.amount || 520.13).toFixed(2)}</span></div>
          </div>
        )}
      </Popup>
    </div>
  )
}

export default Payment
